package cn.ydxiaoshuai.modules.quartz.job;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.ydxiaoshuai.common.api.vo.weixin.WeiXinConts;
import cn.ydxiaoshuai.common.util.RedisUtil;
import cn.ydxiaoshuai.modules.weixin.entity.WeixinAccount;
import cn.ydxiaoshuai.modules.weixin.service.IWeixinAccountService;
import cn.ydxiaoshuai.modules.weixin.util.WXUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author 小帅丶
 * @className WeiXinAccessTokenJob
 * @Description 定时刷新AccessToken
 * @Date 2020/9/10-17:25
 **/
@Component
@Slf4j
public class WeiXinAccessTokenJob implements Job {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IWeixinAccountService weixinAccountService;
    @Autowired
    private WXUtil wxUtil;
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        refreshAccessToken();
    }

    /**
     * @Author 小帅丶
     * @Description 定时刷新AccessToken
     * @Date  2020/9/10 17:27
     * @return void
     **/
    public void refreshAccessToken() {
        log.info("refreshAccessToken执行时间{}", DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        LambdaQueryWrapper<WeixinAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WeixinAccount::getIsEnable, 0);
        List<WeixinAccount> list = weixinAccountService.list(queryWrapper);
        if(list.size()>0){
            log.info("refreshAccessToken公众号数量:{}",list.size());
            list.forEach(weixinAccount -> {
                WeixinAccount one = weixinAccount;
                if(redisUtil.hasKey(one.getAccountCode())){
                    redisUtil.del(one.getAccountCode());
                    WeiXinConts weiXinConts = new WeiXinConts();
                    weiXinConts.setAppid(one.getAccountAppid());
                    weiXinConts.setAppsecret(one.getAccountAppsecret());
                    weiXinConts.setAccess_token(wxUtil.getAccessToken(one));
                    redisUtil.set(one.getAccountCode(), weiXinConts);
                } else {
                    WeiXinConts weiXinConts = new WeiXinConts(one.getAccountAppid(),one.getAccountAppsecret(),wxUtil.getAccessToken(one));
                    redisUtil.set(one.getAccountCode(), weiXinConts);
                }
            });
        }
    }
}
